package com.yexiao.cofe.resolver;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Map;

/**
 * 注解参数解析器
 * @ IRequestParam
 */
public class JSONObjectResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        // 获取注解
        IRequestParam annotation = parameter.getParameterAnnotation(IRequestParam.class);
        return annotation != null && JSONObject.class.isAssignableFrom(parameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Map<String, String[]> parameterMap = webRequest.getParameterMap();
        JSONObject param = new JSONObject(parameterMap.size());
        parameterMap.forEach((k, v) -> {
            if(v.length > 0) {
                param.put(k, v[0]);
            }
        });
        return param;
    }
}
